//
//  Utils.m
//  YOYOLive
//
//  Created by 王根强 on 2016/10/01.
//  Copyright © 2016年 王根强. All rights reserved.
//

#import "Utils.h"

@implementation Utils

+(NSString *)getUUID {
    if ([[KeyChainStore load:@"KEY_USERNAME_PASSWORD"] isEqualToString:@""] || ![KeyChainStore load:@"KEY_USERNAME_PASSWORD"]) {
        //首次执行该方法时，uuid为空
        NSString * strUUID = (NSString *)[KeyChainStore load:@"your_app_bundleID"];
        //生成一个uuid的方法
        CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
        strUUID = (NSString *)CFBridgingRelease(CFUUIDCreateString (kCFAllocatorDefault,uuidRef));
        //将该uuid保存到keychain
        [KeyChainStore save:@"KEY_USERNAME_PASSWORD" data:strUUID];
        return strUUID;
    }else {
        return nil;
    }
}

+ (void)postAppData {
    NSMutableDictionary * postDic = [[NSMutableDictionary alloc] init];
    NSString *url = [NSString stringWithFormat:@"%@%@",@"PRODUCTION_BASE_URL", @"PRODUCTION_BASE_URL"];
    [YONetwork postWithURL:url withParams:postDic withSuccessBlock:^(NSDictionary *dic) {
        if ([dic[@"status"] isEqualToString:@"SUCCESS"]) {
            [UserConfig shareInstance]._updateInfo = [dic[@"data"] objectForKey:@"updateInfo"];
            [UserConfig shareInstance]._iosAuditSwitch = [dic[@"data"] objectForKey:@"iosAuditSwitch"];
            [UserConfig shareInstance]._liveSysTip = [dic[@"data"] objectForKey:@"liveSysTip"];
        }
    } withFailureBlock:^(NSError *error) {
        
    }];
}

+ (BOOL)stringContainsEmoji:(NSString *)string
{
    __block BOOL returnValue = NO;
    
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                const unichar hs = [substring characterAtIndex:0];
                                if (0xd800 <= hs && hs <= 0xdbff) {
                                    if (substring.length > 1) {
                                        const unichar ls = [substring characterAtIndex:1];
                                        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                                        if (0x1d000 <= uc && uc <= 0x1f77f) {
                                            returnValue = YES;
                                        }
                                    }
                                } else if (substring.length > 1) {
                                    const unichar ls = [substring characterAtIndex:1];
                                    if (ls == 0x20e3) {
                                        returnValue = YES;
                                    }
                                } else {
                                    if (0x2100 <= hs && hs <= 0x27ff) {
                                        returnValue = YES;
                                    } else if (0x2B05 <= hs && hs <= 0x2b07) {
                                        returnValue = YES;
                                    } else if (0x2934 <= hs && hs <= 0x2935) {
                                        returnValue = YES;
                                    } else if (0x3297 <= hs && hs <= 0x3299) {
                                        returnValue = YES;
                                    } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                                        returnValue = YES;
                                    }
                                }
                            }];
    return returnValue;
}

+ (BOOL)isContainNULLStr:(NSString *)string {
    for (int i = 0; i < string.length; i++) {
        if ([string characterAtIndex:i] == 32) {
            return YES;
        }
    }
    return NO;
}

+ (BOOL)isPureInt:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}


+ (BOOL)JudgeTheillegalCharacter:(NSString *)content{
    //提示 标签不能输入特殊字符
    NSString *str =@"^[A-Za-z0-9\\u4e00-\u9fa5]+$";
    NSPredicate* emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", str];
    if (![emailTest evaluateWithObject:content]) {
        return YES;
    }
    return NO;
}

+ (BOOL)isContainIllegalCharacter:(NSString *)string {
    NSString *str =@"^[A-Za-z0-9\\u4e00-\u9fa5]+$";
    NSPredicate *stringTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", str];
    if (![stringTest evaluateWithObject:string]) {
        return YES;
    }
    return NO;
}

+ (BOOL)isMobileNumber:(NSString *)mobileNum {
    if (mobileNum.length != 11)
    {
        return NO;
    }
    /**
     * 手机号码:
     * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[0, 1, 6, 7, 8], 18[0-9]
     * 移动号段: 134,135,136,137,138,139,147,150,151,152,157,158,159,170,178,182,183,184,187,188
     * 联通号段: 130,131,132,145,155,156,170,171,175,176,185,186
     * 电信号段: 133,149,153,170,173,177,180,181,189
     */
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|7[0135678]|8[0-9])\\d{8}$";
    /**
     * 中国移动：China Mobile
     * 134,135,136,137,138,139,147,150,151,152,157,158,159,170,178,182,183,184,187,188
     */
    NSString *CM = @"^1(3[4-9]|4[7]|5[0-27-9]|7[08]|8[2-478])\\d{8}$";
    /**
     * 中国联通：China Unicom
     * 130,131,132,145,155,156,170,171,175,176,185,186
     */
    NSString *CU = @"^1(3[0-2]|4[5]|5[56]|7[0156]|8[56])\\d{8}$";
    /**
     * 中国电信：China Telecom
     * 133,149,153,170,173,177,180,181,189
     */
    NSString *CT = @"^1(3[3]|4[9]|53|7[037]|8[019])\\d{8}$";
    
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

+ (BOOL)isValidateEmail:(NSString *)email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

+ (NSString *)uuidString {
    NSString *uuidStr = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    return uuidStr;
}

+ (BOOL)isNetWorkConnecting {
    struct sockaddr zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sa_len = sizeof(zeroAddress);
    zeroAddress.sa_family = AF_INET;
    SCNetworkReachabilityRef defaultRouteReachability =
    SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    BOOL didRetrieveFlags =
    SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    if (!didRetrieveFlags) {
        printf("Error. Count not recover network reachability flags\n");
        return NO;
    }
    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
    BOOL isNetworkEnable  =(isReachable && !needsConnection) ? YES : NO;
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIApplication sharedApplication].networkActivityIndicatorVisible =isNetworkEnable;/*  网络指示器的状态： 有网络 ： 开  没有网络： 关  */
    });
    return isNetworkEnable;
}

+ (BOOL)isAreaCode:(NSString *)areaCode {
    //输入的固话可能带 "-"或者不带 "-" ，所以最好做一个兼容性判断
    //验证输入的固话中不带 "-"符号
    NSString * strNum1 = @"^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$|(^(13[0-9]|15[0|3|6|7|8|9]|18[8|9])\\d{8}$)";
    NSPredicate *checktest1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", strNum1];
    BOOL isAreaCodeWithLinkLine = [checktest1 evaluateWithObject:areaCode];
    
    //验证输入的固话中不带 "-"符号
    NSString * strNum2 = @"^(0[0-9]{2,3})?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$|(^(13[0-9]|15[0|3|6|7|8|9]|18[8|9])\\d{8}$)";
    NSPredicate *checktest2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", strNum2];
    BOOL isAreaCodeWithoutLinkLine = [checktest2 evaluateWithObject:areaCode];
    
    BOOL isAraeCode = isAreaCodeWithLinkLine || isAreaCodeWithoutLinkLine;
    return isAraeCode;
}

+ (NSString *)removeSpaceAndNewline:(NSString *)str {
    NSString *string = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    string = [string stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return string;
}

+ (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

+ (BOOL)validateIdCardNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789Xx"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

+ (BOOL)validateNumberEnglish:(NSString *)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

+ (BOOL)checkIdentityCardNo:(NSString*)identityString {
    if (identityString.length != 18) return NO;
    // 正则表达式判断基本 身份证号是否满足格式
    NSString *regex2 = @"^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$";
    NSPredicate *identityStringPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    //如果通过该验证，说明身份证格式正确，但准确性还需计算
    if(![identityStringPredicate evaluateWithObject:identityString]) return NO;
    
    //** 开始进行校验 *//
    
    //将前17位加权因子保存在数组里
    NSArray *idCardWiArray = @[@"7", @"9", @"10", @"5", @"8", @"4", @"2", @"1", @"6", @"3", @"7", @"9", @"10", @"5", @"8", @"4", @"2"];
    
    //这是除以11后，可能产生的11位余数、验证码，也保存成数组
    NSArray *idCardYArray = @[@"1", @"0", @"10", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2"];
    
    //用来保存前17位各自乖以加权因子后的总和
    NSInteger idCardWiSum = 0;
    for(int i = 0;i < 17;i++) {
        NSInteger subStrIndex = [[identityString substringWithRange:NSMakeRange(i, 1)] integerValue];
        NSInteger idCardWiIndex = [[idCardWiArray objectAtIndex:i] integerValue];
        idCardWiSum+= subStrIndex * idCardWiIndex;
    }
    
    //计算出校验码所在数组的位置
    NSInteger idCardMod=idCardWiSum%11;
    //得到最后一位身份证号码
    NSString *idCardLast= [identityString substringWithRange:NSMakeRange(17, 1)];
    //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
    if(idCardMod==2) {
        if(![idCardLast isEqualToString:@"X"]||[idCardLast isEqualToString:@"x"]) {
            return NO;
        }
    }
    else{
        //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
        if(![idCardLast isEqualToString: [idCardYArray objectAtIndex:idCardMod]]) {
            return NO;
        }
    }
    return YES;
}

//时间转换
+ (NSString *)getShowDateWithTime:(NSString *)time {
    /**
     传入时间转NSDate类型
     */
    NSDate *timeDate = [[NSDate alloc]initWithTimeIntervalSince1970:[time longLongValue]/1000.0];
    
    /**
     初始化并定义Formatter
     :returns: NSDate
     */
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm";
    
    /**
     *  使用Formatter格式化时间（传入时间和当前时间）为NSString
     */
    NSString *timeStr = [dateFormatter stringFromDate:timeDate];
    NSString *nowDateStr = [dateFormatter stringFromDate:[NSDate date]];
    
    /**
     *  判断前四位是不是本年，不是本年直接返回完整时间
     */
    if ([[timeStr substringWithRange:NSMakeRange(0, 4)] rangeOfString:[nowDateStr substringWithRange:NSMakeRange(0, 4)]].location == NSNotFound) {
        return timeStr;
    }else{
        /**
         *  判断是不是本天，是本天返回HH:mm,不是返回MM-dd HH:mm
         */
        if ([[timeStr substringWithRange:NSMakeRange(5, 5)] rangeOfString:[nowDateStr substringWithRange:NSMakeRange(5, 5)]].location != NSNotFound) {
            return [timeStr substringWithRange:NSMakeRange(11, 5)];
        }else{
            return [timeStr substringWithRange:NSMakeRange(5, 11)];
        }
    }
}

//创建签名
+ (NSString *)genSign:(NSMutableDictionary *)signParams {
    // 排序, 因为微信规定 ---> 参数名ASCII码从小到大排序
    NSArray *keys = [signParams allKeys];
    NSArray *sortedKeys = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    //生成 ---> 微信规定的签名格式
    NSMutableString *sign = [NSMutableString string];
    for (NSString *key in sortedKeys) {
        if (!([NSString stringWithFormat:@"%@",[signParams objectForKey:key]] == nil) && ![[NSString stringWithFormat:@"%@",[signParams objectForKey:key]] isEqualToString:@""]  ) {
            [sign appendString:key];
            [sign appendString:@"="];
            [sign appendString:[NSString stringWithFormat:@"%@",[signParams objectForKey:key]]];
            [sign appendString:@"&"];
        }
    }
    NSString *signString = [[sign copy] substringWithRange:NSMakeRange(0, sign.length - 1)];
    // 拼接API密钥
    NSString *result = [NSString stringWithFormat:@"%@&key=%@", signString, @"rongyou4e"];
    // 打印检查
    NSLog(@"result = %@", result);
    // md5加密
    NSString *signMD5 = result.md5Str;
    // 微信规定签名英文大写
    signMD5 = signMD5.uppercaseString;
    // 打印检查
    NSLog(@"signMD5 = %@", signMD5);
    return signMD5;
}

+ (NSString *) compareCurrentTime:(NSString *)str {
    //把字符串转为NSdate
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *timeDate = [dateFormatter dateFromString:str];
    NSDate *currentDate = [NSDate date];
    NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:timeDate];
    long temp = 0;
    NSString *result;
    if (timeInterval/60 < 1) {
        result = [NSString stringWithFormat:@"刚刚"];
    }else if ((temp = timeInterval/60) <60){
        result = [NSString stringWithFormat:@"%ld分钟前",temp];
    }else if ((temp = temp/60) <24){
        result = [NSString stringWithFormat:@"%ld小时前",temp];
    }else if ((temp = temp/24) <30){
        result = [NSString stringWithFormat:@"%ld天前",temp];
    }else if ((temp = temp/30) <12){
        result = [NSString stringWithFormat:@"%ld月前",temp];
    }else {
        temp = temp/12;
        result = [NSString stringWithFormat:@"%ld年前",temp];
    }
    return  result;
}

+ (NSString *)removedStringHuanHang:(NSString *)str {
    NSString *string = str;
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; //去除掉首尾的空白字符和换行字符
    string = [string stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return string;
}

+ (void)isMJRefreshHeaderTarget:(id)target WithTableView:(UITableView *)tableView refreshingAction:(SEL)action {
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:target refreshingAction:action];
    header.lastUpdatedTimeLabel.hidden = YES;
    header.stateLabel.hidden = YES;
    // 设置header
    tableView.mj_header = header;
}

+ (void)isMJRefreshCollectionViewHeaderTarget:(id)target WithTableView:(UICollectionView *)collectionView refreshingAction:(SEL)action {
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:target refreshingAction:action];
    header.lastUpdatedTimeLabel.hidden = YES;
    header.stateLabel.hidden = YES;
    // 设置header
    collectionView.mj_header = header;
}

+ (void)isMJRefreshFooterTarget:(id)target WithTableView:(UITableView *)tableView refreshingAction:(SEL)action {
    MJRefreshAutoFooter *footer = [MJRefreshAutoFooter footerWithRefreshingTarget:target refreshingAction:action];
    tableView.mj_footer = footer;
}

+ (void)isMJRefreshCollectionViewFooterTarget:(id)target WithTableView:(UICollectionView *)collectionView refreshingAction:(SEL)action {
    MJRefreshAutoFooter *footer = [MJRefreshAutoFooter footerWithRefreshingTarget:target refreshingAction:action];
    collectionView.mj_footer = footer;
}

//改变cell右边箭头样式
+ (UIButton *)accessoryView {
    UIImage *image = [UIImage imageNamed:@"main_left_cell"];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    CGRect frame = CGRectMake(0.0,0.0,image.size.width,image.size.height);
    button.frame = frame;
    [button setBackgroundImage:image forState:UIControlStateNormal];
    button.backgroundColor = [UIColor clearColor];
    return button;
}

/**
 *  重写init方法
 */
- (instancetype)initWithDic:(NSDictionary *)dic{
    if (self == [super init]) {
        [self setValuesForKeysWithDictionary:dic];
    }
    return self;
}

+ (instancetype)citiesWithDic:(NSDictionary *)dic{
    return [[self alloc]initWithDic:dic];
}

+ (void)changeUserData {
    NSMutableDictionary * postDic = [[NSMutableDictionary alloc] init];
    [postDic setObject:[UserConfig shareInstance]._appUserID forKey:@"userId"];
    NSString *url = [NSString stringWithFormat:@"%@%@",PRODUCTION_BASE_URL, API_REQUEST_GIVE_USERDATA];
    [YONetwork postWithURL:url withParams:postDic withSuccessBlock:^(NSDictionary *dic) {
        if ([[dic objectForKey:@"status"] isEqualToString:@"SUCCESS"]) {
            //更新用户信息
            NSDictionary *dict = [[dic objectForKey:@"data"] objectForKey:@"userInfo"];
            UserConfig *user = [UserConfig shareInstance];
            user._userBirthday = [dict objectForKey:@"birthday"];
            user._userAddress = [dict objectForKey:@"hometown"];
            user._userConstellation = [dict objectForKey:@"starSign"];
            user._userStatus = [dict objectForKey:@"userStatus"];
            user._userSignature = [dict objectForKey:@"signature"];
            user._userName = [dict objectForKey:@"nickName"];
            user._userScore = [dict objectForKey:@"score"];
            user._userGrade = [dict objectForKey:@"grade"];
            user._userStar = [dict objectForKey:@"star"];
            user._userGoldNumber = [dict objectForKey:@"goldNumber"];
            user._userTicketNumber = [dict objectForKey:@"ticketNumber"];
            user._userGiveZuanNum = [dict objectForKey:@"giveDiamondNumber"];
            user._userGainTicketNumber = [dict objectForKey:@"gainTicketNumber"];
//            user._userFansNum = [dict objectForKey:@"funsNum"];
//            user._userFocusNum = [dict objectForKey:@"concernNum"];
            user._userGender = [dict objectForKey:@"sex"];
            user._userIsR = [dict objectForKey:@"isR"];
            user._isBuyZuan = [dict objectForKey:@"isBuyZuan"];
            user._userUrl = [dict objectForKey:@"head"];
            //user._appYOYOID = [dict objectForKey:@"youboCode"];
            user._userLove = [dict objectForKey:@"emotion"];
            user._mobileNum = [dict objectForKey:@"phone"];
            user._userTag = [dict objectForKey:@"userTag"];
            user._userIsRealName = [dict objectForKey:@"isRealName"];
            user._userScoreMin = [dict objectForKey:@"scoreMin"];
            user._userScoreMax = [dict objectForKey:@"scoreMax"];
            user._userJob = [dict objectForKey:@"job"];
            user._userAge = [dict objectForKey:@"age"];
            user._isSetPayPwd = [dict objectForKey:@"isSetPayPwd"];
            user._userGrade = [dict objectForKey:@"gradePic"];
            //user._userSina = [dict objectForKey:@"sinaWeiBo"];
            user._isLogin = YES;
        }
    } withFailureBlock:^(NSError *error) {
    }];
}


@end
